import requests
import json
from lxml import etree

goodsList_cache = None
goodsList_cache_map = {}


class VipShop():
    def __init__(self):
        self.headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'}

    def getGoodsListByhttp(self):
        param = {
            "functions":"brandShowName,surprisePrice,pcExtra",
            "warehouse":"VIP_NH",
            "mobile_platform":1,
            "app_name":"shop_pc",
            "app_version":"4.0",
            "mars_cid":"1540974927962_20b8b8be78ac0670811db5cc3481359c",
            "fdc_area_id":"104104103",
            #"callback": "categoryMerchandiseInfo1",
            "productIds": "692792352,6917919972458308239,6917926283334275985,6917925037454906257,516334579,689070889,6917920004483683215,689070888,651476867,6917920147859570838,554452569,6917926765696816017,601455893,6917956247242597521,607724062,597629387,654975089,421662703,6917922734045226012,6917920004482376719,669082470,6917919952048378001,6917920004432130703,617713297,6917926992515003612,689070893,6917920376374760335,692597513,687617680,617713293,601455896,662675672,669082465,572880306,676358082,669082466,669082469,6917918070143373892,572880307,676358075,685824902,607724059,630360559,691685639,6917925602484773777,673340765,570996198,679430901,667460202,459541482"
        }



        res = requests.get("http://category.vip.com/ajax/mapi.php?service=product_info",param,headers=self.headers)
        a =  res.content.decode("utf8")
        queryResult = json.loads(a,encoding="ut8")
        if queryResult.get("msg") == 'success':
            return queryResult.get("data",{}).get("products")
        return None


    def getGoodsInfo(self,productId):
        product = goodsList_cache_map[productId]
        if not product:
            return {"msg":"查询失败"}
        info = product.get("info",None)
        if info:
            return product
        brandId = product["brandId"]
        url = "https://detail.vip.com/detail-%s-%s.html"%(brandId,productId)
        self.goodsInfoSend(url,product)
        return product



    def goodsInfoSend(self,url,product):
         res = requests.get(url,headers=self.headers)
         html = etree.HTML(res.content)
         imgs = html.xpath('//div[@class="pic-sliderwrap"]//div[contains(@class,"show-midpic")]/a/@href')
         info = product["info"] = {};
         info["imgs"] = imgs


    def run(self):
        global goodsList_cache
        goodsList = self.getGoodsListByhttp();
        if not goodsList:
            print("唯品会数据获取失败")
            return
        goodsList_cache = goodsList
        for item in goodsList_cache:
            productId = item["productId"];
            goodsList_cache_map[productId] = item
            #self.getGoodsInfo(productId)





